const sql = require('mssql');
const baseFn = require('../../public/base.js');

/**
 * @description 入库拒收
 */



// 查询供应商信息
const getStorageRefuseCustomer = async (ctx) => {
    try {

        const { GYSBM } = ctx.request.body;
        let selectSql = `SELECT KHYH,YHZH,BM,MC,CASE WHEN (ISNULL(DH,'')= '' OR ISNULL(SJ,'')= '') THEN DH+SJ ELSE DH+'/'+SJ END AS DH,DZ,LXR 
        FROM BM_WLDW WHERE DWLX = 1  AND BM = '${GYSBM}'`;
        let selectResult = await sql.query(selectSql);
        ctx.body = { success: true, result: selectResult.recordset[0] }
    } catch (err) {
        ctx.body = { success: false, err }
    }
}


// 查询商品信息
const getStorageRefuseShop = async (ctx) => {
    try {
        const { ypbmList } = ctx.request.body;
        let bmList = ypbmList.map(item => `'${item}'`).join(',');
        let selectSql = `SELECT Y.BM,Y.MC,Y.TYMC,Y.GG,Y.JLDW,Y.JXMC,Y.SCCJ,Y.PZWH,Z.YPPHGZ FROM BM_YP Y LEFT JOIN YPPHGZ Z ON Y.BM = Z.YPBM WHERE Y.QY_FLAG = 'T' AND BM IN (${bmList})`;
        let selectResult = await sql.query(selectSql);
        ctx.body = { success: true, result: selectResult.recordset }
    } catch (err) {
        ctx.body = { success: false, err }
    }
}

// 生成id
const createId = async (userId, tableName) => {
    let lastOrderSql = `SELECT TOP 1 ID_JSD FROM ${tableName} WHERE ID_JSD LIKE '${baseFn.getNowTimeId().date}${userId}12%' ORDER BY ID DESC`;
    let oldOrder = await sql.query(lastOrderSql);
    let newSerialNum = 1;
    if (oldOrder.recordset.length !== 0) {
        let oldOrderId = oldOrder.recordset[0].ID_JSD;
        let oldSerialNum = oldOrderId.slice(oldOrderId.length - 4);
        newSerialNum = Number(oldSerialNum) + 1;
    }
    newSerialNum = newSerialNum.toString();
    newSerialNum = '0000'.slice(0, 4 - newSerialNum.length) + newSerialNum;
    return baseFn.getNowTimeId().date + userId + '12' + newSerialNum;
}


// 保存拒收单
const keepStorageRefuseInfo = async (ctx) => {
    try {
        const { queryList, shopList } = ctx.request.body;
        let jsdId = await createId(queryList.userId, 'GSP_YPJSBGD');
        let insertSql = ` INSERT INTO [dbo].[GSP_YPJSBGD]( [BMBM], [BMMC], [YPBM], [TYMC], [YPMC], [JXMC], [YPGG], [PZWH], [SCCJ], [GJQY], [JLDW],
         [SL], [SCPH], [YXQZ], [JSYY],  [DJ], [JE], [JSLX], [DWBM], [CGYMC], [JSRMC], [THFS],[ID_JSD],[RQ]) `;
        shopList.forEach((item, ind) => {
            let dj = item.DJ ? Number(item.DJ) : 0;
            let sl = item.JSSL ? Number(item.JSSL) : 0;
            let je = (dj * sl).toFixed(2);
            insertSql += ` SELECT '${queryList.BMBM ? queryList.BMBM : 'NULL'}','${queryList.BMMC}','${item.BM}','${item.TYMC ? item.TYMC : 'NULL'}','${item.MC}','${item.JXMC}',
            '${item.GG}','${item.PZWH}','${item.SCCJ}','${queryList.GJQY}','${item.JLDW}',${sl},'${item.SCPH}',
            '${item.YXQZ}','${item.JSYY}',${dj},${je},'${item.JSLX}','${queryList.GYSBM}','${queryList.CGYMC}','${queryList.JSRMC}',
            '${queryList.THFS}','${jsdId}','${baseFn.getNowTimeId().fullDate}' `;
            if (ind !== shopList.length - 1) {
                insertSql += ' UNION ';
            }
        });
        let selectResult = await sql.query(insertSql);
        if (selectResult.rowsAffected[0] > 0) {
            ctx.body = { success: true, id: jsdId }
        } else {
            ctx.body = { success: false }
        }

    } catch (err) {
        ctx.body = { success: false, err }
    }
}


module.exports = {
    'POST /getStorageRefuseCustomer': getStorageRefuseCustomer,
    'POST /getStorageRefuseShop': getStorageRefuseShop,
    'POST /keepStorageRefuseInfo': keepStorageRefuseInfo
}